package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.uu.utils.PriceTextChangedListener;
import com.android.uu.utils.uuUtils;
import com.android.uu.view.ActionSheetDialog;
import com.android.uu.view.ActionSheetDialog.OnSheetItemClickListener;
import com.android.uu.view.ActionSheetDialog.SheetItemColor;
import com.hemaapp.BaseConfig;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.AddImageAdapter;
import com.hemaapp.yjnh.bean.BlogType;
import com.hemaapp.yjnh.bean.CustomAddition;
import com.hemaapp.yjnh.bean.CustomBlogDetail;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.Img;
import com.hemaapp.yjnh.bean.ImgItemsBean;
import com.hemaapp.yjnh.bean.ProvinceCityDistrict;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.db.CityDBClient;
import com.hemaapp.yjnh.view.DateSelectDialog;
import com.hemaapp.yjnh.view.ImageGridView;
import com.hemaapp.yjnh.view.ProvinceCityDialog;
import com.hemaapp.yjnh.view.WheelSelectorDialog;
import com.hemaapp.yjnh.view.YjnhImageWay;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import xtom.frame.util.XtomFileUtil;
import xtom.frame.util.XtomImageUtil;
import xtom.frame.util.XtomToastUtil;

/**
 * 发布定制产品
 */
public class ReleaseCustomizeActivity extends BaseActivity implements OnClickListener {

    private final static int REQUEST_CAMERA = 0x01;
    private final static int REQUEST_ALBUM = 0x02;

    @Bind(R.id.image_grid)
    ImageGridView imageGrid;
    @Bind(R.id.tv_on_shelf)
    TextView tvOnShelf;
    @Bind(R.id.tv_off_shelf)
    TextView tvOffShelf;
    @Bind(R.id.edt_name)
    EditText edtName;
    @Bind(R.id.tv_type)
    TextView tvType;
    @Bind(R.id.edt_price)
    EditText edtPrice;
    @Bind(R.id.edt_score)
    EditText edtScore;
    @Bind(R.id.edt_old_score)
    EditText edtOldPrice;
    @Bind(R.id.tv_unit)
    TextView tvUnit;
    @Bind(R.id.edt_range)
    EditText edtRange;
    @Bind(R.id.tv_date)
    TextView tvDate;
    @Bind(R.id.tv_address)
    TextView tvAddress;
    @Bind(R.id.edt_package)
    EditText edtPackage;
    @Bind(R.id.edt_spec)
    EditText edtSpec;
    @Bind(R.id.edt_content)
    EditText edtContent;
    @Bind(R.id.image_detail_grid)
    ImageGridView imageDetailGrid;
    @Bind(R.id.layout_addition)
    LinearLayout layoutAddition;
    @Bind(R.id.title_right_btn)
    Button titleRightBtn;
    @Bind(R.id.title_text)
    TextView titleText;

    private CustomBlogDetail blog;//在需改已经发布过的商品时会用到
    private String saleflag = "1";//农货售卖状态	0：关闭；1：进行中
    private String blog_id = "0";//商品id
    private User user;
    private ArrayList<String> types = new ArrayList<>();
    private ArrayList<String> units = new ArrayList<>();
    private YjnhImageWay imageWay;
    private int curImage;//在拍照和调用相册时使用：0轮播图片，1商品详情图片,2以及以后为附加费用图片
    private int upAddtionOrder = 0;//上传的附加属性的排序：0第一个附加属性，1第二个附加属性，以此类推
    private AddImageAdapter autoAdapter;
    private AddImageAdapter detailAdapter;
    private ArrayList<ImgItemsBean> delImages = new ArrayList<>();//待删除的网络图片
    private ArrayList<ImgItemsBean> autoImg = new ArrayList<>();//轮播图片
    private ArrayList<ImgItemsBean> detailsImg = new ArrayList<>();//详情图片
    private ArrayList<EditText> additionContent = new ArrayList<>();
    private ArrayList<EditText> additionPrice = new ArrayList<>();
    private ArrayList<ArrayList<ImgItemsBean>> additionImages = new ArrayList<>();
    private ArrayList<AddImageAdapter> additionAdapter = new ArrayList<>();
    private ArrayList<CustomAddition> additions = new ArrayList<>();
    private ArrayList<CustomAddition> additionDel = new ArrayList<>();//待删除的附加费用
    private ArrayList<Integer> imgOrders = new ArrayList<>();//上传图片的排序,依次是轮播图、商品详情图、附加费用图1、附加费用图2、……
    private ProvinceCityDialog addressDialog;
    private DateSelectDialog dateSelectDialog;
    private ArrayList<String> compressPaths;//压缩图片的路径，用于最后删除
    CityDBClient cityDBClient;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_release_customize);
        ButterKnife.bind(this);
        user = getApplicationContext().getUser();
        super.onCreate(savedInstanceState);
        imageWay = new YjnhImageWay(mContext, REQUEST_ALBUM, REQUEST_CAMERA) {
            @Override
            public void album() {
                // 注意：若不重写该方法则使用系统相册选取(对应的onActivityResult中的处理方法也应不同)
                Intent it = new Intent(mContext, AlbumActivity.class);
                int size = 4;
                if (curImage == 0)
                    size = autoImg.size();
                else if (curImage == 1)
                    size = detailsImg.size();
                else if (curImage >= 2) {
                    size = additionImages.get(curImage-2).size();
                }
                it.putExtra("limitCount", 4 - size);// 图片选择张数限制
                it.putExtra("model", 1);// 图片是单选还是多选
                startActivityForResult(it, albumRequestCode);
            }
        };
        if (!blog_id.equals("0"))
            getNetWorker().getCustomBlog("", blog_id);
        else {
            //给轮播图和详情图添加图片顺序
            imgOrders.add(0);
            imgOrders.add(0);
            refreshADImages();
            refreshDetailImages();
        }
        //获取作物分类和单位
        getNetWorker().getBlogTypeList("3", "0");
        getNetWorker().getBlogTypeList("5", "0");
        //获取所有的城市
        cityDBClient = new CityDBClient(mContext);
        if (cityDBClient.getDataCount() == 0) {
            getNetWorker().getDistrictList("-2");
        }
    }

    @Override
    protected void findView() {
    }

    @Override
    protected void getExras() {
        blog_id = mIntent.getStringExtra("blog_id");
        if (isNull(blog_id)) {
            blog_id = "0";
        }
    }

    @Override
    protected void setListener() {
        if (blog_id.equals("0"))
            titleText.setText("发布定制");
        else
            titleText.setText("编辑定制");
        titleRightBtn.setText("确定");
        edtPrice.addTextChangedListener(new PriceTextChangedListener(2, edtPrice));
        edtScore.addTextChangedListener(new PriceTextChangedListener(2, edtScore));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //删除在上传本地图片过程中生成的临时压缩图片
        if (compressPaths != null)
            for (String path : compressPaths) {
                File file = new File(path);
                file.delete();
            }
    }
    /**
     * 如果是修改已经发布过的商品
     * 那么将商品信息显示到编辑框中
     */
    private void setData() {
        if (blog.getSaleflag().equals("1")) {//1上架；0下架
            tvOnShelf.setTextColor(getResources().getColor(R.color.text_orange));
            tvOffShelf.setTextColor(getResources().getColor(R.color.text_grey));
            saleflag = "1";
        }else if (blog.getSaleflag().equals("0")) {
            tvOnShelf.setTextColor(getResources().getColor(R.color.text_grey));
            tvOffShelf.setTextColor(getResources().getColor(R.color.text_orange));
            saleflag = "0";
        }
        edtName.setText(blog.getName());
        tvType.setText(blog.getTypename());
        edtPrice.setText(uuUtils.formatAfterDot2(blog.getPrice()));
        edtScore.setText(uuUtils.formatAfterDot2(blog.getScore()));
        edtOldPrice.setText(uuUtils.formatAfterDot2(blog.getOldprice()));
        tvUnit.setText(blog.getGood_unit());
        edtRange.setText(blog.getYield_range());
        tvDate.setText(blog.getSend_date());
        tvAddress.setText(blog.getSend_address());
        edtPackage.setText(blog.getPackage_style());
        edtSpec.setText(blog.getSpec());
        edtContent.setText(blog.getContent());
        autoImg.clear();
        autoImg.addAll(blog.getImgItems());
        detailsImg.clear();
        detailsImg.addAll(blog.getImg2Items());
        refreshADImages();
        refreshDetailImages();
        additions = (ArrayList<CustomAddition>) blog.getAddItems();
        for (CustomAddition addition:additions) {
            addAddtiton(addition);
        }
        //分别计算三类图片的顺序
        try {
            imgOrders.clear();
            int max = 0;
            for (ImgItemsBean item : autoImg) {
                int orderby = Integer.parseInt(item.getOrderby());
                max = orderby > max ? orderby:max;
            }
            imgOrders.add(max+1);
            max = 0;
            for (ImgItemsBean item : detailsImg) {
                int orderby = Integer.parseInt(item.getOrderby());
                max = orderby > max ? orderby:max;
            }
            imgOrders.add(max+1);
            for (ArrayList<ImgItemsBean> images : additionImages) {
                max = 0;
                for (ImgItemsBean item : images) {
                    int orderby = Integer.parseInt(item.getOrderby());
                    max = orderby > max ? orderby : max;
                }
                imgOrders.add(max + 1);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CUSTOM_BLOG_GET:
            case FILE_UPLOAD:
            case BLOGTYPE_LIST:
            case CUSTOM_GOODS_ADD:
            case IMG_DELOPERATE:
            case CUSTOM_ADDITION_ADD:
            case BLOG_SAVEOPERATE:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case FILE_UPLOAD:
            case CUSTOM_BLOG_GET:
            case BLOGTYPE_LIST:
            case CUSTOM_GOODS_ADD:
            case IMG_DELOPERATE:
            case CUSTOM_ADDITION_ADD:
            case BLOG_SAVEOPERATE:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CUSTOM_BLOG_GET:
                HemaArrayResult<CustomBlogDetail> bResult = (HemaArrayResult<CustomBlogDetail>) baseResult;
                blog = bResult.getObjects().get(0);
                if (blog == null) {
                    showTextDialog("获取商品信息失败！");
                    titleText.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            finish();
                        }
                    }, 1000);
                } else {
                    setData();
                }
                break;
            case CUSTOM_GOODS_ADD:
                HemaArrayResult<String> sResult = (HemaArrayResult<String>) baseResult;
                blog_id = sResult.getObjects().get(0);
                if (blog != null) {
                    blog_id = blog.getId();
                } else {
                    blog_id = sResult.getObjects().get(0);
                }
                //删掉要删除的图片
                if (delImages.size() > 0) {
                    delNetImage();
                }else if (additionDel.size() > 0) {
                    delAddition();
                }else {
                    upAutoImages();
                }
                break;
            case FILE_UPLOAD:
                String keytype = netTask.getParams().get("keytype");
                if (keytype.equals("20")) {//上传完一张轮播图，开始上传下一张轮播图
                    autoImg.remove(0);
                    upAutoImages();
                }else if (keytype.equals("21")) {//上传完一张详情图，开始上传下一张详情图
                    detailsImg.remove(0);
                    upDetailImages();
                } else if (keytype.equals("22")) {
                    additionImages.get(upAddtionOrder).remove(0);
                    upAdditonImages();
                }
                break;
            case CUSTOM_ADDITION_ADD:
                HemaArrayResult<String> sResult2 = (HemaArrayResult<String>) baseResult;
                additions.get(upAddtionOrder).setId(sResult2.getObjects().get(0));
                upAdditonImages();//添加完一个附加费用之后，就去上传它的图片
                break;
            case IMG_DELOPERATE:
                delImages.remove(0);
                if (delImages.size() > 0) {
                    delNetImage();
                }else if (additionDel.size() > 0) {
                    delAddition();
                }else {
                    upAutoImages();
                }
                break;
            case BLOGTYPE_LIST:
                HemaArrayResult<BlogType> typeResult = (HemaArrayResult<BlogType>) baseResult;
                if (typeResult == null || typeResult.getObjects() == null)
                    return;
                String keytype1 = netTask.getParams().get("keytype");
                if (keytype1.equals("3")) {
                    ArrayList<BlogType> types = new ArrayList<>();
                    types.clear();
                    types.addAll(typeResult.getObjects());
                    for (BlogType type : types) {
                        this.types.add(type.getName());
                    }
                }else if (keytype1.equals("5")) {
                    ArrayList<BlogType> units = new ArrayList<>();
                    units.clear();
                    units.addAll(typeResult.getObjects());
                    for (BlogType type : units) {
                        this.units.add(type.getName());
                    }
                }
                break;
            case BLOG_SAVEOPERATE:
                upAutoImages();
                break;
            case DISTRICT_LIST:
                HemaPageArrayResult<ProvinceCityDistrict> result = (HemaPageArrayResult<ProvinceCityDistrict>) baseResult;
                ArrayList<ProvinceCityDistrict> districts = result.getObjects();
                if (districts != null && districts.size() > 0) {
                    new SaveDistrictTask().execute(districts);
                }
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CUSTOM_GOODS_ADD:
                XtomToastUtil.showShortToast(mContext, "发布失败，"+baseResult.getMsg());
                break;
            case FILE_UPLOAD:
                XtomToastUtil.showShortToast(mContext, "图片上传失败，"+baseResult.getMsg());
                break;
            case CUSTOM_BLOG_GET:
                XtomToastUtil.showShortToast(mContext, "获取商品信息失败，"+baseResult.getMsg());
                break;
            case IMG_DELOPERATE:
                XtomToastUtil.showShortToast(mContext, "图片删除失败，"+baseResult.getMsg());
                break;
            case CUSTOM_ADDITION_ADD:
                XtomToastUtil.showShortToast(mContext, "保存失败，"+baseResult.getMsg());
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CUSTOM_GOODS_ADD:
                XtomToastUtil.showShortToast(mContext, "发布失败，请稍候再试");
                break;
            case FILE_UPLOAD:
                XtomToastUtil.showShortToast(mContext, "图片上传失败，请稍候再试");
                break;
            case CUSTOM_BLOG_GET:
                XtomToastUtil.showShortToast(mContext, "获取商品信息失败，请稍候再试");
                break;
            case IMG_DELOPERATE:
                XtomToastUtil.showShortToast(mContext, "图片删除失败，请稍候再试");
                break;
            case CUSTOM_ADDITION_ADD:
                XtomToastUtil.showShortToast(mContext, "保存失败，请稍候再试");
                break;
        }
    }

    private void delNetImage() {
        ImgItemsBean item = delImages.get(0);
        getNetWorker().imgDel(user.getToken(), item.getId());
    }

    private void delAddition() {
        StringBuffer ids = new StringBuffer();
        for (CustomAddition item : additionDel) {
            ids.append(item.getId()).append(",");
        }
        if (ids.length() > 0)
            ids.deleteCharAt(ids.length()-1);
        getNetWorker().blogSaveoperate(user.getToken(), "7", ids.toString());
    }

    /**
     * 上传轮播图
     */
    private void upAutoImages() {
        if (autoImg.size() > 0) {
            String imagePath = autoImg.get(0).getImgurl();
            if (!imagePath.startsWith("http")) {//只上传新的图片
                getNetWorker().fileUpload(user.getToken(), "20", blog_id,
                        "0", imgOrders.get(0) + "", "无", imagePath);
                int order = imgOrders.get(0);
                imgOrders.set(0, order+1);
            }else {
                autoImg.remove(0);
                upAutoImages();
            }
        }else {
            upDetailImages();
        }
    }

    /**
     * 上传详细介绍
     */
    private void upDetailImages() {
        if (detailsImg.size() > 0) {
            String imagePath = detailsImg.get(0).getImgurl();
            if (!imagePath.startsWith("http")) {//只上传新的图片
                getNetWorker().fileUpload(user.getToken(), "21", blog_id,
                        "0", imgOrders.get(1) + "", "无", imagePath);
                int order = imgOrders.get(1);
                imgOrders.set(1, order+1);
            }else {
                detailsImg.remove(0);
                upDetailImages();
            }
        }else {//开始上传附加属性
            if (additionPrice.size() > 0) {
                upAddtionOrder = 0;
                getNetWorker().addCustomAddition(user.getToken(), blog_id,
                        additionPrice.get(upAddtionOrder).getText().toString(),
                        additionContent.get(upAddtionOrder).getText().toString(),
                        additions.get(upAddtionOrder).getId());
            }else {
                showTextDialog("发布成功!");
                EventBusMsg msg = new EventBusMsg();
                msg.setType(EventBusConfig.NEW_CUSTOM_BLOG);
                EventBus.getDefault().post(msg);
                titleText.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        setResult(RESULT_OK);
                        finish();
                    }
                }, 1500);
            }
        }
    }

    /**
     * 上传附加属性的照片
     */
    private void upAdditonImages() {
        ArrayList<ImgItemsBean>  images = additionImages.get(upAddtionOrder);
        if (images.size() > 0) {
            String imagePath = images.get(0).getImgurl();
            if (!imagePath.startsWith("http")) {//只上传新的图片
                getNetWorker().fileUpload(user.getToken(), "22", additions.get(upAddtionOrder).getId(),
                        "0", imgOrders.get(upAddtionOrder) + "", "无", imagePath);
                int order = imgOrders.get(upAddtionOrder);
                imgOrders.set(upAddtionOrder, order+1);
            }else {//继续添加下一个
                images.remove(0);
                upAdditonImages();
            }
        }else {
            upAddtionOrder++;
            if (additionPrice.size() > upAddtionOrder) {
                getNetWorker().addCustomAddition(user.getToken(), blog_id,
                        additionPrice.get(upAddtionOrder).getText().toString(),
                        additionContent.get(upAddtionOrder).getText().toString(),
                        additions.get(upAddtionOrder).getId());
            }else {
                showTextDialog("发布成功!");
                EventBusMsg msg = new EventBusMsg();
                msg.setType(EventBusConfig.NEW_CUSTOM_BLOG);
                EventBus.getDefault().post(msg);
                titleText.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        setResult(RESULT_OK);
                        finish();
                    }
                }, 1500);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (RESULT_OK != resultCode) {
            return;
        }
        switch (requestCode) {
            case REQUEST_ALBUM:// 相册选择图片
                album(data);
//                albumSys(data);
                break;
            case REQUEST_CAMERA:// 拍照
                camera();
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @OnClick({R.id.tv_on_shelf, R.id.tv_off_shelf, R.id.tv_type, R.id.tv_unit, R.id.tv_date,
            R.id.tv_address, R.id.tv_add_addition, R.id.title_left_btn, R.id.title_right_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.title_right_btn:
                String name = edtName.getText().toString();
                final String type = tvType.getText().toString();
                String price = edtPrice.getText().toString();
                String score = edtScore.getText().toString();
                String oldPrice = edtOldPrice.getText().toString();
                String unit = tvUnit.getText().toString();
                String range = edtRange.getText().toString();
                String date = tvDate.getText().toString();
                String address = tvAddress.getText().toString();
                String packet = edtPackage.getText().toString();
                String spec = edtSpec.getText().toString();
                String content = edtContent.getText().toString();
                if (autoImg.size() == 0) {
                    XtomToastUtil.showShortToast(mContext, "农作物图片不能为空");
                    return;
                }
                if (detailsImg.size() == 0) {
                    XtomToastUtil.showShortToast(mContext, "详情图片不能为空");
                    return;
                }
                if (isNull(name) || isNull(type) || isNull(price) || isNull(oldPrice) || isNull(score) ||
                        isNull(unit) || isNull(range) || isNull(date) || isNull(address) ||
                        isNull(packet) ||isNull(spec) ||isNull(content) ) {
                    XtomToastUtil.showShortToast(mContext, "请输入完整信息");
                    return;
                }
                for (int i=0;i<additionPrice.size();i++) {
                    if(isNull(additionPrice.get(i).getText().toString())) {
                        XtomToastUtil.showShortToast(mContext, "请填写附加费用价格");
                        return;
                    }
                    if(isNull(additionContent.get(i).getText().toString())) {
                        XtomToastUtil.showShortToast(mContext, "请填写附加费用内容");
                        return;
                    }
                }
                try {
                    double price2 = Double.parseDouble(price);
                    double score2 = Double.parseDouble(score);
                    double priceOld2 = Double.parseDouble(oldPrice);
                    if (price2 > 100000000) {
                        XtomToastUtil.showShortToast(mContext, "商品价格不能高于100,000,000元");
                        return;
                    }
                    if (priceOld2 > 100000000) {
                        XtomToastUtil.showShortToast(mContext, "商品原价不能高于100,000,000元");
                        return;
                    }
                    if (score2 > 100000000) {
                        XtomToastUtil.showShortToast(mContext, "可用粮票不能高于100,000,000元");
                        return;
                    }
                    if (score2 > price2) {
                        XtomToastUtil.showShortToast(mContext, "粮票价格不能高于商品价格");
                        return;
                    }
                    if (price2 == 0 && score2 == 0) {
                        XtomToastUtil.showShortToast(mContext, "不能发布0元商品");
                        return;
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }
                getNetWorker().addCustomGoods(user.getToken(), name, price, oldPrice, score, unit, range,
                        date, address, packet, spec, type, content, blog_id, saleflag);
                break;
            case R.id.tv_on_shelf:
                tvOnShelf.setTextColor(getResources().getColor(R.color.text_orange));
                tvOffShelf.setTextColor(getResources().getColor(R.color.text_grey));
                saleflag = "1";
                break;
            case R.id.tv_off_shelf:
                tvOnShelf.setTextColor(getResources().getColor(R.color.text_grey));
                tvOffShelf.setTextColor(getResources().getColor(R.color.text_orange));
                saleflag = "0";
                break;
            case R.id.tv_type:
                if (types.size() == 0) {
                    XtomToastUtil.showShortToast(mContext, "暂无定制类型");
                    return;
                }
                WheelSelectorDialog wheelDialog = new WheelSelectorDialog(mContext).builder();
                wheelDialog.setListener(new WheelSelectorDialog.onSelectedItemListener() {
                    @Override
                    public void onSelected(int index) {
                        tvType.setText(types.get(index));
                    }
                });
                wheelDialog.setDatas(types);
                wheelDialog.show();
                break;
            case R.id.tv_unit:
                if (units.size() == 0) {
                    XtomToastUtil.showShortToast(mContext, "暂无定制单位");
                    return;
                }
                WheelSelectorDialog wheelDialog2 = new WheelSelectorDialog(mContext).builder();
                wheelDialog2.setListener(new WheelSelectorDialog.onSelectedItemListener() {
                    @Override
                    public void onSelected(int index) {
                        tvUnit.setText(units.get(index));
                    }
                });
                wheelDialog2.setDatas(units);
                wheelDialog2.show();
                break;
            case R.id.tv_date:
                if (dateSelectDialog == null) {
                    dateSelectDialog = new DateSelectDialog(mContext).builder();
                    dateSelectDialog.setListener(new DateSelectDialog.onSelectedItemListener() {
                        @Override
                        public void onSelected(String year, String month, String day) {
                            tvDate.setText(year+"-"+month+"-"+day);
                        }
                    });
                }
                dateSelectDialog.show();
                break;
            case R.id.tv_address:
                if (addressDialog == null) {
                    addressDialog = new ProvinceCityDialog(mContext).builder();
                    addressDialog.setListener(new ProvinceCityDialog.onSelectedItemListener() {
                        @Override
                        public void onSelected(int province, int city, int county) {
//                            String addressStr = "";
                            String provinceStr = "";
                            String cityStr = "";
                            String countyStr = "";
//                            if (province == 0)
//                                provinceStr = "全国";
//                            else
//                                provinceStr = addressDialog.getProvinceDatas().get(province);
//                            if (city != 0) {
//                                cityStr = addressDialog.getCityDatas().get(city);
//                                if (county != 0) {
//                                    countyStr = addressDialog.getCountyDatas().get(county);
//                                    addressStr = provinceStr + cityStr + countyStr;
//                                } else {
//                                    addressStr = provinceStr + cityStr;
//                                }
//                            } else {
//                                addressStr = provinceStr;
//                            }
//                            tvAddress.setText(addressStr);
                            provinceStr = addressDialog.getProvinceDatas().get(province);
                            cityStr = addressDialog.getCityDatas().get(city);
                            countyStr = addressDialog.getCountyDatas().get(county);
                            if (cityStr.equals("暂无"))
                                cityStr = "";
                            if (countyStr.equals("暂无"))
                                countyStr = "";
                            tvAddress.setText(provinceStr + cityStr + countyStr);
                        }
                    });
                }
                addressDialog.show();
                break;
            case R.id.tv_add_addition:
                CustomAddition addition = new CustomAddition();
                addition.setId("0");
                additions.add(addition);
                addAddtiton(addition);
                break;
        }
    }

    /**
     * 添加一个附加费用
     */
    private void addAddtiton(CustomAddition addition) {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        final LinearLayout layout = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.layout_customize_addition, null);
        final EditText edtAdditionContent = (EditText) layout.findViewById(R.id.edt_addition_content);
        additionContent.add(edtAdditionContent);
        EditText edtAdditionPrice = (EditText) layout.findViewById(R.id.edt_addition_price);
        edtAdditionPrice.addTextChangedListener(new PriceTextChangedListener(2, edtAdditionPrice));
        additionPrice.add(edtAdditionPrice);
        ImageGridView gridAddition = (ImageGridView) layout.findViewById(R.id.image_addition_grid);
        TextView tvDelete = (TextView) layout.findViewById(R.id.tv_delete);
        tvDelete.setTag(addition);
        tvDelete.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                final CustomAddition addition1 = (CustomAddition) v.getTag();
                HemaButtonDialog dialog = new HemaButtonDialog(mContext);
                dialog.setText("删除该附加费用?");
                dialog.setLeftButtonText("取消");
                dialog.setRightButtonText("确定");
                dialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

                    @Override
                    public void onRightButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                        try {
                            additionDel.add(addition1);
                            int position = additions.indexOf(addition1);
                            layoutAddition.removeViewAt(position);
                            additions.remove(position);
                            additionContent.remove(position);
                            additionPrice.remove(position);
                            additionImages.remove(position);
                            additionAdapter.remove(position);
                            imgOrders.remove(position+2);
                        }catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onLeftButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                    }
                });
            }
        });
        //设置数据
        ArrayList<ImgItemsBean> images = new ArrayList<>();
        if (!addition.getId().equals("0")) {//非新增
            edtAdditionContent.setText(addition.getContent());
            edtAdditionPrice.setText(addition.getPrice());
            images = (ArrayList<ImgItemsBean>) addition.getImgItems();
        }else {
            imgOrders.add(0);
        }
        additionImages.add(images);
        final AddImageAdapter adapter = new AddImageAdapter(mContext, images);
        adapter.setShowDelete(false);
        additionAdapter.add(adapter);
        adapter.setImageClickListener(new AddImageAdapter.OnImageClickListener() {
            @Override
            public void onImageClickListener(int position) {
                int index = additionContent.indexOf(edtAdditionContent);
                if (additionImages.get(index).size() < 5 && position == additionImages.get(index).size()) {
                    curImage = index+2;
                    showPic();
                }else if (position < additionImages.get(index).size()){
                    showImageOpe(position, additionImages.get(index), adapter);
                }
            }

            @Override
            public void onDeleteClickListener(int position, ImgItemsBean item) {
                int index = additionContent.indexOf(edtAdditionContent);
                if (item.getImgurl().startsWith("http"))
                    delImages.add(item);
                additionImages.get(index).remove(position);
                additionAdapter.get(index).notifyDataSetChanged();
            }
        });
        gridAddition.setAdapter(adapter);
        layoutAddition.addView(layout, lp);
    }

    /**
     * 刷新轮播图片
     */
    private void refreshADImages() {
        if (autoAdapter == null) {
            autoAdapter = new AddImageAdapter(mContext, autoImg);
            autoAdapter.setShowDelete(false);
            imageGrid.setAdapter(autoAdapter);
            autoAdapter.setImageClickListener(new AddImageAdapter.OnImageClickListener() {
                @Override
                public void onImageClickListener(int position) {
                    if (autoImg.size() < 5 && position == autoImg.size()) {
                        curImage = 0;
                        showPic();
                    }else if (position < autoImg.size()){
                        showImageOpe(position, autoImg, autoAdapter);
                    }
                }

                @Override
                public void onDeleteClickListener(int position, ImgItemsBean imageItem) {
                    if (imageItem.getImgurl().startsWith("http"))
                        delImages.add(imageItem);
                    autoImg.remove(position);
                    autoAdapter.notifyDataSetChanged();
                }
            });
        } else {
            autoAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 刷新详情图片
     */
    private void refreshDetailImages() {
        if (detailAdapter == null) {
            detailAdapter = new AddImageAdapter(mContext, detailsImg);
            detailAdapter.setShowDelete(false);
            imageDetailGrid.setAdapter(detailAdapter);
            detailAdapter.setImageClickListener(new AddImageAdapter.OnImageClickListener() {
                @Override
                public void onImageClickListener(int position) {
                    if (detailsImg.size() < 5 && position == detailsImg.size()) {
                        curImage = 1;
                        showPic();
                    }else if (position < detailsImg.size()){
                        showImageOpe(position, detailsImg, detailAdapter);
                    }
                }

                @Override
                public void onDeleteClickListener(int position, ImgItemsBean imageItem) {
                    if (imageItem.getImgurl().startsWith("http"))
                        delImages.add(imageItem);
                    detailsImg.remove(position);
                    detailAdapter.notifyDataSetChanged();
                }
            });
        } else {
            detailAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 显示图片选择对话
     */
    public void showPic() {
        new ActionSheetDialog(mContext)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("相机", SheetItemColor.Black,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                imageWay.camera();
                            }
                        })
                .addSheetItem("从相册打开", SheetItemColor.Black,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                imageWay.album();
                            }
                        })
                .show();
    }

    private void camera() {
        String imagepath = imageWay.getCameraImage();
        new CompressPicTask().execute(imagepath);
    }

    private void album(Intent data) {
        if (data == null)
            return;
        ArrayList<String> imgList = data.getStringArrayListExtra("images");
        if (imgList == null)
            return;
        for (String img : imgList) {
            new CompressPicTask().execute(img);
        }
    }

//    /**处理系统相册
//     * @param data
//     */
//    private void albumSys(Intent data) {
//        if (data == null)
//            return;
//        String picturePath = null;
//        Uri selectedImage = data.getData();
//        String[] filePathColumn = {MediaStore.Images.Media.DATA};
//        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
//        if (cursor != null) {
//            cursor.moveToFirst();
//            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//            picturePath = cursor.getString(columnIndex);
//            cursor.close();
//            cursor = null;
//
//            if (picturePath == null || picturePath.equals("null")) {
//                Toast toast = Toast.makeText(mContext, "抱歉，没有找到图片", Toast.LENGTH_SHORT);
//                toast.setGravity(Gravity.CENTER, 0, 0);
//                toast.show();
//                return;
//            }
//        } else {
//            File file = new File(selectedImage.getPath());
//            if (!file.exists()) {
//                Toast toast = Toast.makeText(mContext, "抱歉，没有找到图片", Toast.LENGTH_SHORT);
//                toast.setGravity(Gravity.CENTER, 0, 0);
//                toast.show();
//                return;
//
//            }
//            picturePath = file.getAbsolutePath();
//        }
//        new CompressPicTask().execute(picturePath);
//    }

    /**
     * 压缩图片
     */
    private class CompressPicTask extends AsyncTask<String, Void, Integer> {
        String compressPath;

        @Override
        protected Integer doInBackground(String... params) {
            try {
                String path = params[0];
                String savedir = XtomFileUtil.getTempFileDir(mContext);
                compressPath = XtomImageUtil.compressPictureWithSaveDir(path,
                        BaseConfig.IMAGE_HEIGHT, BaseConfig.IMAGE_WIDTH,
                        BaseConfig.IMAGE_QUALITY, savedir, mContext);
                return 0;
            } catch (Exception e) {
                return 1;
            }
        }

        @Override
        protected void onPreExecute() {
            showProgressDialog("正在压缩图片");
        }

        @Override
        protected void onPostExecute(Integer result) {
            cancelProgressDialog();
            switch (result) {
                case 0:
                    if (compressPaths == null)
                        compressPaths = new ArrayList<>();
                    compressPaths.add(compressPath);
                    ImgItemsBean imageitem = new ImgItemsBean();
                    imageitem.setImgurl(compressPath);
                    imageitem.setImgurlbig(compressPath);
                    if (curImage == 0) {
                        autoImg.add(imageitem);
                        refreshADImages();
                    }else if (curImage == 1) {
                        detailsImg.add(imageitem);
                        refreshDetailImages();
                    }else if (curImage >= 2) {
                        additionImages.get(curImage-2).add(imageitem);
                        additionAdapter.get(curImage-2).notifyDataSetChanged();
                    }
                    break;
                case 1:
                    showTextDialog("图片压缩失败");
                    break;
            }
        }
    }
    private void showImageOpe(final int position, final ArrayList<ImgItemsBean> images, final AddImageAdapter adapter) {
        new ActionSheetDialog(mContext)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("查看大图", SheetItemColor.Black,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                ArrayList<Img> imgs = new ArrayList<Img>();
                                for (int i = 0; i < images.size(); i++) {
                                    ImgItemsBean item = images.get(i);
                                    String imgurl_detail = item.getImgurlbig();
                                    Img img = new Img(imgurl_detail);
                                    imgs.add(img);
                                }

                                Intent intent = new Intent();
                                intent.setClass(mContext, ShowLargeImageActivity.class);
                                intent.putExtra("imgs", imgs);
                                intent.putExtra("position", position + 1);
                                mContext.startActivity(intent);
                            }
                        })
                .addSheetItem("删除", SheetItemColor.Black,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                ImgItemsBean imageItem = images.get(position);
                                if (imageItem.getImgurl().startsWith("http"))
                                    delImages.add(imageItem);
                                images.remove(position);
                                adapter.notifyDataSetChanged();
                            }
                        })
                .show();
    }
    private class SaveDistrictTask extends AsyncTask<ArrayList<ProvinceCityDistrict>, Void, Void> {

        @Override
        protected void onPreExecute() {
            showProgressDialog("正在保存");
        }

        @Override
        protected Void doInBackground(ArrayList<ProvinceCityDistrict>... params) {
            cityDBClient.clear();
            for (ProvinceCityDistrict district : params[0]) {
                cityDBClient.insert(district);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void v) {
            cancelProgressDialog();
        }
    }
}
